//
//  BubbleBgView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/8/5.
//  气泡背景图
//

import SwiftUI

struct BubbleBgView: View {
    @State var bubble: BubbleBean
    @State private var switchTimer: Timer?
    @State private var currentIndex = 0

    var body: some View {
        //设置一个透明的背景图，然后往这个背景图设置 挂件
        ZStack {
            Color.clear //占用试图，保证跟Text一样大小
            // 添加四个角挂件
                .overlay(alignment: .topLeading) {
                    if let iconBubble = bubble.iconLeftTop, let icon = iconBubble.icon {
                        cornerImage(name: icon, offset: CGSize(width: iconBubble.x, height: iconBubble.y))
                    }
                }
                .overlay(alignment: .topTrailing) {
                    if let iconBubble = bubble.iconRightTop, let icon = iconBubble.icon {
                        cornerImage(name: icon, offset: CGSize(width: iconBubble.x, height: iconBubble.y))
                    }
                }
                .overlay(alignment: .bottomLeading) {
                    if let iconBubble = bubble.iconLeftBottom, let icon = iconBubble.icon {
                        cornerImage(name: icon, offset: CGSize(width: iconBubble.x, height: iconBubble.y))
                    }
                }
                .overlay(alignment: .bottomTrailing) {
                    if let iconBubble = bubble.iconRightBottom, let icon = iconBubble.icon {
                        cornerImage(name: icon, offset: CGSize(width: iconBubble.x, height: iconBubble.y))
                    }
                }
            
        }
        //在背景图在设置一层真真的拉伸背景图
            .background{
                ZStack {
                    
                    if let icons = bubble.iconCenter?.icons, icons.isEmpty == false {
                        Image(icons[currentIndex])
                    } else if let icon = bubble.iconCenter?.icon {
                        Image(icon)
                    }
                }.padding(.leading , bubble.iconCenter?.leading ?? 0)
                    .padding(.trailing, bubble.iconCenter?.trailing ?? 0)
                    .padding(.top , bubble.iconCenter?.top ?? 0)
                    .padding(.bottom , bubble.iconCenter?.bottom ?? 0)
            }
        // 快速切换时，关闭隐式动画（避免过度渲染）
            .animation(nil, value: currentIndex)
            .onAppear {
                startSwitching()
            }
            .onDisappear {
                stopSwitching()
            }
    }
    
    
    
    // 角标视图构建函数
    private func cornerImage(name: ImageResource, offset: CGSize) -> some View {
        Image(name)
            .offset(offset)
    }
    
    // 启动切换定时器
    private func startSwitching() {
        if let iconCenter = bubble.iconCenter, let icons = iconCenter.icons, !icons.isEmpty {
            stopSwitching() // 先停止旧定时器
            
            let interval = iconCenter.time ?? 0.05 // 确保间隔不为0，避免立即触发
            let timer = Timer(timeInterval: interval, repeats: true) { _ in
                DispatchQueue.main.async {
                    self.currentIndex = (self.currentIndex + 1) % icons.count
                }
            }
            
            // 将定时器添加到 RunLoop 的 common 模式（关键修改），不然列表拖动就会停止
            RunLoop.main.add(timer, forMode: .common)
            switchTimer = timer // 保存定时器引用
        }
    }
    
    // 停止切换定时器
    private func stopSwitching() {
        switchTimer?.invalidate()
        switchTimer = nil
    }
}

#Preview {
    BubbleBgView(bubble: BubbleExt.getBubble(id: "30") ?? BubbleBean())
}
